package cn.edu.ctbu.demo1.service;

import cn.edu.ctbu.demo1.constant.REnum;
import cn.edu.ctbu.demo1.dao.StudentRepository;
import cn.edu.ctbu.demo1.entity.Student;
import cn.edu.ctbu.demo1.exception.RException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class StudentService {
    @Autowired
    public StudentRepository studentRepository;


    public List<Student> getAll(){

        return studentRepository.findAll();
    }

    public Page<Student> getAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }
    public Page<Student>getAll(Example<Student>example,Pageable pageable){
        return studentRepository.findAll(example,pageable);
    }






    public Student findById(int id){

        return studentRepository.findById(id).get();
    }


    public List<Student> findByName(String name){

        return studentRepository.findByNameLike(name);
    }


    public  List<Student> findByNameAndPassword(String name,String password){
        return  studentRepository.findByNameAndPassword(name, password);
    }

    public void insert(Student student){

        studentRepository.save(student);
    }

    public Object update(Student student){

        studentRepository.save(student);
        return null;
    }
    public void delete(Integer id){

        studentRepository.deleteById(id);
    }

    public Student add(Student student) {
        return studentRepository.save(student);
    }

    public Student gengxin(Student student) {
        return studentRepository.save(student);
    }

    public void shanchu(Integer id) {
        studentRepository.deleteById(id);
    }

    public Student validateUsernameAndPassword(String sno,String password) throws Exception {

        List<Student> students=studentRepository.findBySno(sno);
        if(students.size()>0){
            //可能对password加密，但我们不能暂时处理
            Student student=students.get(0);
            if (student.getPassword().equals(password)){
                //成功
                return student;
            }else {
                throw new RException(REnum.LOGIN_ERR);
            }


        }else {
            throw new RException(REnum.LOGIN_ERR);
        }




    }


}
